package com.example.demo810.cfg;

import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 *
 * tomcat启动之后，会发布一个ServletWebServerInitializedEvent事件。
 * 熟悉spring事件机制的朋友都会知道，事件event,和监听器Listener是共同存在的，通过观察者模式来完成spring的事件机制。
 *
 *
 *
 * 获取本项目运行时的IP和端口
 * @author lzh
 * @date 2020/8/11 - 17:37
 */
@Component
public class MyServerListener implements ApplicationListener<WebServerInitializedEvent> {
    private int serverPort;

    public int getServerPort() {
        return serverPort;
    }

    public void setServerPort(int serverPort) {
        this.serverPort = serverPort;
    }

    public String getUrl() {
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return "http://"+address.getHostAddress()+":"+this.serverPort;
    }

    public String getHost() {
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return address.getHostAddress();
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent webServerInitializedEvent) {
        serverPort = webServerInitializedEvent.getWebServer().getPort();
    }
}
